package net.jeeframework.fileuplod.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeeframework.fileuplod.FileInfo;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = -6580547176191508357L;

	private static final Log log = LogFactory.getLog(UploadServlet.class);

	private static final int MaxMemorySize = 1024 * 1024 * 1024;

	private static final long MaxRequestSize = FileInfo.M * 1024;

	private static final File TempDirectory = new File("d:/temp/");

	private static final String storageDirectory = "d:/upload/";

	private static final boolean writeToFile = true;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			log.debug("==> uploading file at:" + format.format(new Date()));

			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory(MaxMemorySize, TempDirectory);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			upload.setSizeMax(MaxRequestSize);

			// Parse the request
			List /* FileItem */items = upload.parseRequest(request);

			// Process the uploaded items
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String fieldName = item.getFieldName();
					String fileName = item.getName();
					String contentType = item.getContentType();
					long sizeInBytes = item.getSize();
					boolean isInMemory = item.isInMemory();

					FileInfo fileInfo = new FileInfo(fileName, sizeInBytes, contentType);

					log.debug("==> upload file: "+fileInfo);

					// Process a file upload
					if (writeToFile) {
						String fullPath = storageDirectory + File.separator + fileInfo.getFileId();
						File uploadedFile = new File(fullPath);
						String path = uploadedFile.getParent();
						File saveDir = new File(path);
						if (!saveDir.exists()) {
							saveDir.mkdirs();
						}
						item.write(uploadedFile);
					} else {
						InputStream uploadedStream = item.getInputStream();
						uploadedStream.close();
					}
				}
			}

			log.debug("==> file upload complate : " + format.format(new Date()));

		} catch (Exception e) {
			log.error(e);
		}

	}
}
